package net.pws.oos.biz.service.impl;

import java.util.List;

import net.pws.common.persistence.EntityManager;
import net.pws.oos.biz.model.Attachment;
import net.pws.oos.biz.model.PhotoMarker;
import net.pws.oos.biz.service.AttachmentService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class DefaultAttachmentService implements AttachmentService {

	@Autowired
	private EntityManager entityManager;

	public Attachment saveAttachment(Attachment attachment) {
		entityManager.persist(attachment);
		return attachment;
	}

	@Override
	public Attachment saveAttachment(Attachment attachment,
			List<PhotoMarker> photoMarkers) {
		attachment = saveAttachment(attachment);
		for(PhotoMarker photoMarker : photoMarkers) {
			photoMarker.setMediaId(attachment.getId());
			savePhotoMarker(photoMarker);
		}
		return attachment;
	}

	@Override
	public PhotoMarker savePhotoMarker(PhotoMarker photoMarker) {
		entityManager.persist(photoMarker);
		return photoMarker;
	}

	@Override
	public void deletePhotoMarkers(String photoId) {
		String hql = "delete PhotoMarker where mediaId=? ";
		entityManager.execute(hql, new Object[] { photoId });
	}

	@Override
	public void savePhotoMarkers(List<PhotoMarker> photoMarkers) {
		for(PhotoMarker photoMarker : photoMarkers) {
			savePhotoMarker(photoMarker);
		}
	}

	@Override
	public void updatePhotoMarkers(Attachment attachment,
			List<PhotoMarker> markers) {
		deletePhotoMarkers(attachment.getId());
		for(PhotoMarker photoMarker : markers) {
			photoMarker.setMediaId(attachment.getId());
			savePhotoMarker(photoMarker);
		}
	}

}
